// edit页面键盘事件
import { computed } from 'vue'
import { onKeyStroke } from '@vueuse/core'
import { useEditStore } from '@/store'
import { ElMessage } from 'element-plus'
import { on, off } from '@/libs/tools'
import useWidget from '@/libs/edit/widgetData'
import useWidgetView from '@/libs/edit/widgetView'
import usePageHistory from '@/libs/edit/pageHistory'

export default function useEditKeydownEvents() {
    const editStore = useEditStore()

    const {
        widgetListFlat,
        onDeleteWidget,
        onCopyWidegt,
        getWidgetLevelStatus,
        onSetWidgetLevel
    } = useWidget()

    const {
        getWidgetViewDom
    } = useWidgetView()

    const {
        isBackPageHistory,
        isForwardPageHistory,
        onBackPageHistory,
        onForwardPageHistory,
        onAddPageHistory
    } = usePageHistory()

    const pageId = computed(() => editStore.pageId)

    // 当前选中控件ID集
    const selectWidgetIds = computed(() => editStore.selectWidgetIds)

    onKeyStroke(e => {
        // 只响应 body 的键盘事件 (避免响应 input 等的键盘事件)
        if (e?.target?.localName !== 'body') return

        editKeydownEvents(e)
    })

    // 编辑页键盘事件
    function editKeydownEvents(event) {
        let { ctrlKey, shiftKey, key } = event
        key = key.toLowerCase()

        if (selectWidgetIds.value.length > 0) {
            const widget = widgetListFlat.value[selectWidgetIds.value[0]]
            // 是否是自由子控件
            const isFreeWidget = widget?.isFreeWidget || false
            
            // 复制
            if (ctrlKey && (key === 'c')) {
                onCopyWidegt({
                    toPageId: pageId.value,
                    widgetIds: selectWidgetIds.value
                })
            }
            // 删除
            else if (key === 'delete') {
                onDeleteWidget(selectWidgetIds.value)
                onAddPageHistory()
            }
            // 图层置顶
            else if (ctrlKey && shiftKey && (key === 'arrowup') && isFreeWidget) {
                if (getWidgetLevelStatus(selectWidgetIds.value) === 'top') return
                onSetWidgetLevel({
                    widgetIds: selectWidgetIds.value,
                    type: 'top'
                })
            }
            // 图层置底
            else if (ctrlKey && shiftKey && (key === 'arrowdown') && isFreeWidget) {
                if (getWidgetLevelStatus(selectWidgetIds.value) === 'bottom') return
                onSetWidgetLevel({
                    widgetIds: selectWidgetIds.value,
                    type: 'bottom'
                })
            }
            // 图层上移
            else if (ctrlKey && (key === 'arrowup') && isFreeWidget) {
                if (getWidgetLevelStatus(selectWidgetIds.value) === 'top') return
                onSetWidgetLevel({
                    widgetIds: selectWidgetIds.value,
                    type: 'moveup',
                    step: 1
                })
            }
            // 图层下移
            else if (ctrlKey && (key === 'arrowdown') && isFreeWidget) {
                if (getWidgetLevelStatus(selectWidgetIds.value) === 'bottom') return
                onSetWidgetLevel({
                    widgetIds: selectWidgetIds.value,
                    type: 'movedown',
                    step: 1
                })
            }
            // 位置移动(上下左右)
            else if (['arrowup', 'arrowdown', 'arrowleft', 'arrowright'].includes(key) && isFreeWidget) {
                event.preventDefault()
                setWidgetPosition({
                    topStep: ['arrowup', 'arrowdown'].includes(key) ? ((key === 'arrowup') ? -1 : 1) : 0,
                    leftStep: ['arrowleft', 'arrowright'].includes(key) ? ((key === 'arrowleft') ? -1 : 1) : 0
                })
            }
        }

        // 操作记录后退
        if (ctrlKey && (key === 'z')) {
            if (isBackPageHistory.value) {
                onBackPageHistory()
            } else {
                ElMessage({
                    message: '到底了哦',
                    type: 'info',
                    grouping: true
                })
            }
        }
        // 操作记录前进
        else if (ctrlKey && (key === 'y')) {
            if (isForwardPageHistory.value) {
                onForwardPageHistory()
            } else {
                ElMessage({
                    message: '到底了哦',
                    type: 'info',
                    grouping: true
                })
            }
        }
        // 保存
        else if (ctrlKey && (key === 's')) {
            event.preventDefault()
            saveData()
        }
    }

    let saveLoading = false
    let saveMessageRef = null
    // 保存
    function saveData() {
        if (saveLoading) {
            ElMessage({
                showClose: true,
                message: '操作太频繁啦',
                type: 'info',
                grouping: true
            })
            return
        }
        saveLoading = true
        saveMessageRef = ElMessage({
            showClose: true,
            message: '保存中...',
            type: 'info',
            grouping: true
        })
        editStore.saveAppData().finally(() => {
            saveLoading = false
            saveMessageRef.close()
        })
    }

    let widgetDoms = {}
    let widgetDomFrame = null
    /**
     * 设置控件位置
     * @param {Number} topStep 距上步长
     * @param {Number} leftStep 距左步长
     */
     const setWidgetPosition = ({ topStep, leftStep }) => {
        widgetDoms = {}
        selectWidgetIds.value.forEach(id => {
            const dom = getWidgetViewDom(id)
            widgetDoms[id] = {
                dom,
                position: {
                    top: parseInt(dom.style.top),
                    left: parseInt(dom.style.left),
                    newTop: parseInt(dom.style.top),
                    newLeft: parseInt(dom.style.left)
                }
            }
        })
        widgetDomFrame = requestAnimationFrame(() => {
            Object.values(widgetDoms).forEach(item => {
                const left = parseInt(item.position.left) + leftStep
                const top = parseInt(item.position.top) + topStep
                item.dom.style.cssText += `left:${left}px;top:${top}px;`
                item.position.newTop = top
                item.position.newLeft = left
            })
        })
        // 创建键盘松开事件(当松开键盘时再去更新控件数据，这样可以优化性能)
        on(document.body, 'keyup', updateWidgetStyleData)
    }

    // 更新控件样式数据
    function updateWidgetStyleData() {
        selectWidgetIds.value.forEach(id => {
            const { widgetData } = widgetListFlat.value[id]
            widgetData.eles.style.left = `${widgetDoms[id].position.newLeft}px`
            widgetData.eles.style.top = `${widgetDoms[id].position.newTop}px`
        })
        cancelAnimationFrame(widgetDomFrame)
        // 销毁键盘松开事件
        off(document.body, 'keyup', updateWidgetStyleData)
    }
}